
package mr.ali.videoapp.portal;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Component
@ConfigurationProperties(prefix = "wechat")
public class WeChatConfig {

    private String appid;
    private String secret;

    // 缓存 access_token
    private final Map<String, String> tokenCache = new ConcurrentHashMap<>();
    private final AtomicLong expiresTime = new AtomicLong(0); // 过期时间戳（毫秒）

    private static final String ACCESS_TOKEN_URL =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 获取 access_token（带本地缓存）
     */
    public synchronized String getAccessToken() {
        long now = System.currentTimeMillis();
        if (now < expiresTime.get()) {
            return tokenCache.get("access_token");
        }

        try {
            String url = String.format(ACCESS_TOKEN_URL, appid, secret);
            @SuppressWarnings("rawtypes")
            Map response = restTemplate.getForObject(url, Map.class);
            if (response != null && response.containsKey("access_token")) {
                String token = (String) response.get("access_token");
                int expiresIn = (Integer) response.get("expires_in"); // 通常为7200秒

                tokenCache.put("access_token", token);
                expiresTime.set(now + (expiresIn - 60) * 1000); // 提前60秒过期
                return token;
            } else {
                throw new RuntimeException("获取 access_token 失败: " + response);
            }
        } catch (Exception e) {
            throw new RuntimeException("调用微信获取 access_token 接口异常", e);
        }
    }

    // getter and setter
    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

//package mr.ali.videoapp.portal;
//
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.stereotype.Component;
//
//@Component
//@ConfigurationProperties(prefix = "wechat")
//public class WeChatConfig {
//    private String appid;
//    private String secret;
//
//    // 必须生成 getter 和 setter
//    public String getAppid() {
//        return appid;
//    }
//
//    public void setAppid(String appid) {
//        this.appid = appid;
//    }
//
//    public String getSecret() {
//        return secret;
//    }
//
//    public void setSecret(String secret) {
//        this.secret = secret;
//    }
//}
